#include "string.h"

/* returns the length of s */
int32_t strlen(const char* s){
  int32_t i;
  for(i=0; s[i] != '\0'; i++);
  return i;
}

/* copy up to n characters from source to destination and returns a pointer to destination */
char* strncpy(char* destination, const char* source, int32_t n){
  int32_t i;
  for(i=0;i<n-1 && source[i] != '\0';i++)
    destination[i] = source[i];
  destination[i] = '\0';
  return destination;
}

/* concatenate up to n characters from source to destination and returns a pointer to destination */
char* strncat(char* destination, const char* source, int32_t n){
  int32_t i, j;
  /* go to end of destination string */
  for(i=0;i<n-1 && destination[i] != '\0';i++);
  /* append content of source to destination */
  for(j=0;i+j<n-1 && source[j] != '\0';j++)
    destination[i+j] = source[j];
  destination[i+j] = '\0';
  return destination;
}

/* compare two strings and returns:
   a positive number if s1 > s2
   0 if s1 == s2
   a negative number if s1 < s2 
*/
int32_t strcmp(const char* s1, const char* s2){
  int32_t i = 0;
  while(s1[i] == s2[i] && s1[i++] != '\0');
  return s1[i] - s2[i];
}

/* converts value into a character string and stores it into string (up to n-1 characters). At the end, string is a null terminated character string. Returns also a pointer to string. */
char* itoa(int32_t value, char* string, uint32_t n){
  int32_t k,j = 0,i = 0;
  char tmp;
  if(!n)
    return string;
  if(n == 1){
    string[0] = '\0';
    return string;
  }

  if(value < 0){
    string[i++] = '-';
    value *= -1;
    j = 1;
  }
  do{
    string[i++] = '0' + value%10;
    value /= 10; 
  }while(value != 0 && i < n-1);
  //now, the int representation is inverted (42 -> 24), we need to put it the other way around
  k = i - 1;
  while(k-j > 0){
    tmp = string[j];
    string[j++] = string[k];
    string[k--] = tmp;
  }
  string[i] = '\0';
  return string;
}

/* converts string into a signed int and returns it. Returns 0 if string is not a number. */
int32_t atoi(const char* string){
  int32_t tmp, i, negative = 0, return_value = 0, end = 0, k = 1;
  if(string[0] == '-'){
    negative = 1;
    end = 1;
  }
  for(i = strlen(string)-1; i >= end ; i--){
    tmp = string[i] - '0'; //if string[i] is a number, it gives the correct int
    if(tmp < 0 || tmp > 9)
      //Not a number
      return 0;
    return_value += tmp * k;
    k*= 10;
  }
  return (negative?return_value*-1:return_value);
}
